package com.haoxuer.discover.user.data.dao.impl;

import com.haoxuer.discover.data.core.CriteriaDaoImpl;
import com.haoxuer.discover.data.page.Filter;
import com.haoxuer.discover.rest.base.ResponseObject;
import com.haoxuer.discover.user.data.dao.UserBindDao;
import com.haoxuer.discover.user.data.entity.UserBind;
import com.haoxuer.discover.user.data.enums.BindType;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * Created by imake on 2018年10月31日10:33:01.
 */
@Repository

public class UserBindDaoImpl extends CriteriaDaoImpl<UserBind, Long> implements UserBindDao {

  @Override
  public UserBind findById(Long id) {
    if (id == null) {
      return null;
    }
    return get(id);
  }

  @Override
  public UserBind save(UserBind bean) {

    getSession().save(bean);


    return bean;
  }

  @Override
  public UserBind deleteById(Long id) {
    UserBind entity = super.get(id);
    if (entity != null) {
      getSession().delete(entity);
    }
    return entity;
  }

  public UserBind findByType(String no, BindType type) {
    return one(Filter.eq("bindType",type),Filter.eq("no",no));
  }

  @Override
  public UserBind findByUser(Long user, BindType type) {
    return one(Filter.eq("bindType",type),Filter.eq("user.id",user));
  }

  @Override
  public UserBind findByUserName(String username) {
    return findByType(username, BindType.account);
  }

  @Override
  public UserBind findByName(String name) {
    UserBind bind=  findByUserName(name);
    if (bind==null){
      bind=  findByEmail(name);
    }
    if (bind==null){
      bind=  findByPhone(name);
    }
    return bind;
  }

  @Override
  public UserBind findByPhone(String phone) {
    return findByType(phone, BindType.phone);
  }

  @Override
  public UserBind findByEmail(String email) {
    return findByType(email, BindType.email);
  }

  @Override
  public ResponseObject checkNo(String no, BindType type) {
    ResponseObject result = new ResponseObject();
    UserBind bind = findByType(no, type);
    if (bind != null) {
      result.setCode(-1);
      result.setMsg("已使用");
      return result;
    }
    return result;
  }

  @Override
  protected Class<UserBind> getEntityClass() {
    return UserBind.class;
  }

  @Autowired
  public void setSuperSessionFactory(SessionFactory sessionFactory) {
    super.setSessionFactory(sessionFactory);
  }
}